using IQIGame.Onigao.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace IQIGame.Onigao.GamePlay
{
    public class RectIntJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Game.RectInt);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                JToken jObject = JToken.Load(reader);
                int x = jObject["X"].Value<int>();
                int y = jObject["Y"].Value<int>();
                int width = jObject["Width"].Value<int>();
                int height = jObject["Height"].Value<int>();

                // 创建并返回一个 RectInt 实例
                return new Game.RectInt(x, y, width, height);
            }
            catch (Exception e)
            {
                LogGame.LogError(e);
                return new Game.RectInt();
            }

        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Game.RectInt rect = (Game.RectInt)value;
            JObject jObject = new JObject
            {
                { "X", rect.X },
                { "Y", rect.Y },
                { "Width", rect.Width },
                { "Height", rect.Height }
            };
            jObject.WriteTo(writer);
        }
    }
}
